import { extend, trim, map } from "lodash";
import React, { useState, useEffect } from "react";
import { useDebouncedCallback } from "use-debounce";
import { Section, Input, Select, ContextHelp } from "@/components/visualizations/editor";
import { formatSimpleTemplate } from "@/lib/value-format";
import { axios } from "@/services/axios";

function Editor({ column, onChange }) {
  const [queries, setQueries] = useState([]);
  const [onChangeDebounced] = useDebouncedCallback(onChange, 200);

  useEffect(() => {
    axios.get("api/queries/recent").then((mapResults) => {
      setQueries(mapResults);
    })
  }, []);

  return queries && queries.length>0 && (
    <React.Fragment>
    <Section>
      <Select
        label="显示样式"
        defaultValue={column.selectDisplay || ''}
        onChange={value => onChange({ selectDisplay: value })}
      >
        <Select.Option value="">下拉选择</Select.Option>
        <Select.Option value="option">按钮选择</Select.Option>
        <Select.Option value="button">开关选择</Select.Option>
      </Select>
    </Section>
    <Section>
      <Select
        label="选择查询"
        defaultValue={column.query_id}
        showSearch
        optionFilterProp="name"
        onChange={value => onChange({ query_id: value })}
      >
        {map(queries, q => (
          <Select.Option value={q.id}>{q.name}</Select.Option>
        ))}
      </Select>
    </Section>
    <Section>
      <Input
        label={
          <React.Fragment>
            默认值
            <ContextHelp.FunctionFormatSpecs />
          </React.Fragment>
        }
        defaultValue={column.defaultValue}
        onChange={event => onChange({ defaultValue: event.target.value })}
      />
    </Section>
    </React.Fragment>
  );
}

export default function initQueryColumn(column) {
  function prepareData(row) {
    row = extend({ "@": row[column.name] }, row);

    const src = trim(formatSimpleTemplate(column.imageUrlTemplate, row));
    if (src === "") {
      return {};
    }

    const width = parseInt(formatSimpleTemplate(column.imageWidth, row), 10);
    const height = parseInt(formatSimpleTemplate(column.imageHeight, row), 10);
    const title = trim(formatSimpleTemplate(column.imageTitleTemplate, row));

    const result = { src };

    if (Number.isFinite(width) && width > 0) {
      result.width = width;
    }
    if (Number.isFinite(height) && height > 0) {
      result.height = height;
    }
    if (title !== "") {
      result.text = title; // `text` is used for search
      result.title = title;
      result.alt = title;
    }

    return result;
  }

  function ImageColumn({ row }) {
    // eslint-disable-line react/prop-types
    const { text, ...props } = prepareData(row);
    return <img alt="" {...props} />;
  }

  ImageColumn.prepareData = prepareData;

  return ImageColumn;
}

initQueryColumn.friendlyName = "查询结果";
initQueryColumn.Editor = Editor;
